<?php

namespace app\admin\model;

use think\Model;


class SalesReturn extends Model
{





    // 表名
    protected $name = 'sales_return';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = false;

    // 定义时间戳字段名
    protected $createTime = false;
    protected $updateTime = false;
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'return_reason_text',
        'refund_status_text',
        'name',
        'tax_amount',
        'total_amount'
    ];
    protected $schema = [
        'id' => 'int(11)',
        'name' => 'varchar(255)',
        'shipment_id' => 'int(11)',
        'invoice_number' => 'varchar(100)',
        'return_reason' => 'varchar(50)',
        'return_date' => 'date',
        'refund_status' => 'varchar(50)',
        'refund_amount' => 'decimal(10,2)',
        'currency' => 'varchar(3)',
        'is_inventory_updated' => 'tinyint(1)',
        'remarks' => 'text',
        'quantity' => 'int(11)',
        'unit' => 'varchar(20)',
        'tax_rate' => 'int(11)'
    ];


    public function getReturnReasonList()
    {
        return ['质量问题' => __('质量问题'), '发错货' => __('发错货'), '客户取消' => __('客户取消'), '运输损坏' => __('运输损坏'), '其他' => __('其他')];
    }

    public function getRefundStatusList()
    {
        return ['未退款' => __('未退款'), '已退款' => __('已退款'), '部分退款' => __('部分退款')];
    }


    public function getReturnReasonTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['return_reason']) ? $data['return_reason'] : '');
        $list = $this->getReturnReasonList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getRefundStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['refund_status']) ? $data['refund_status'] : '');
        $list = $this->getRefundStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    public function getTaxAmountAttr($value, $data)
    {
        $refundAmount = isset($data['refund_amount']) ? $data['refund_amount'] : 0;
        $taxRate = isset($data['tax_rate']) ? $data['tax_rate'] : 0;

        // 计算税额：税额 = 含税金额 - 不含税金额
        // 不含税金额 = 含税金额 / (1 + 税率/100)
        // 税额 = 含税金额 - 不含税金额 = 含税金额 × (税率/100) / (1 + 税率/100)
        $taxAmount = $refundAmount * ($taxRate / 100) / (1 + $taxRate / 100);

        return round($taxAmount, 2);
    }

    public function getTotalAmountAttr($value, $data)
    {
        $refundAmount = isset($data['refund_amount']) ? $data['refund_amount'] : 0;
        $taxRate = isset($data['tax_rate']) ? $data['tax_rate'] : 0;

        // 计算不含税价格：价格(不含税) = 含税金额 / (1 + 税率/100)
        $priceWithoutTax = $refundAmount / (1 + $taxRate / 100);

        return round($priceWithoutTax, 2);
    }


}
